package com.ymatou.iapi.quickturnover.service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ymatou.iapi.quickturnover.parameter.ApplyAdvanceBillBean;
import com.ymatou.iapi.quickturnover.parameter.CreateAdvanceOrderReqBean;
import com.ymatou.iapi.quickturnover.parameter.GetSellerAdvanceInfoReqBean;
import com.ymatou.iapi.quickturnover.parameter.GrantCreditReqBean;
import com.ymt.base.YmatouEasyCall;
import com.ymt.core.tool.Logger;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.database.model.AdvanceOrder;
import com.ymttest.database.sqlwapper.AdvanceOrderDefaultWapper;
import com.ymttest.utils.EnvSetup;

public class AdvanceOrderService {

	public static String billCode_sit1 = "BH000000674YM";
	public static String billCode_uat = "BH000000706YM";

	//创建预支单
	public static Map createAdvanceOrder() {
		Map map = new HashMap();
		try {
			OrderCallService orderService = new OrderCallService();

			map = orderService
					.createM2cOrder(com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum.SailProtect);

			int orderId = (Integer) map.get("orderId");
			int sellerId = (Integer) map.get("sellerId");
			int userId = (Integer) map.get("userId");
			int tradingId = (Integer) map.get("tradingId");

			BigDecimal totalPrice = (BigDecimal) map.get("totalPrice");// 支付金额
			// 买家付款
			orderService.orderPayRequest(userId, totalPrice, tradingId);
			// 接单
			orderService.acceptOrder(orderId, sellerId);

			YmatouEasyCall SaveDeliverSummaryCall = new YmatouEasyCall("",
					"POST", "JSON");
			String BillCode = EnvSetup.getEnv().equals("sit1")
					? billCode_sit1
					: billCode_uat;

			StringBuffer saveDeliverSummaryString = new StringBuffer();
			saveDeliverSummaryString
					.append("{\"SaveDeliverSummaryInfos\":[{\"BillCode\":\"");
			saveDeliverSummaryString.append(BillCode);
			saveDeliverSummaryString.append("\",");
			saveDeliverSummaryString
					.append("\"CanReDelivery\":0,\"DeliverType\":2,\"ExpressCode\":\"xlobo\",\"InnerExpressCode\":\"\",\"IsChinaDeliver\":false,");
			saveDeliverSummaryString.append("\"OrderId\":");
			saveDeliverSummaryString.append(orderId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString
					.append("\"Provider\":\"洋码头官方合作物流（xLobo贝海国际速递）\",");
			saveDeliverSummaryString.append("\"SellerId\":");
			saveDeliverSummaryString.append(sellerId);
			saveDeliverSummaryString.append(",");
			saveDeliverSummaryString.append("\"Weight\":10}]}");
			SaveDeliverSummaryCall
					.setUrl("http://api.seller.ymatou.com/api/Deliver/SaveDeliverSummary");

			SaveDeliverSummaryCall.setData(saveDeliverSummaryString.toString());
			Logger.comment("发货处理");
			SaveDeliverSummaryCall.callService();
			//商家发货 
			orderService.dispatchedByXlobo(orderId, sellerId);
			//创建预支单
			Logger.comment("创建预支单");
			CreateAdvanceOrderReqBean createadvanceorderreqBean = new CreateAdvanceOrderReqBean();
			CreateAdvanceOrderReqCall createadvanceorderreqCall = new CreateAdvanceOrderReqCall();
			createadvanceorderreqBean.setOrderId(orderId);
			createadvanceorderreqCall.setData(false, createadvanceorderreqBean);
			createadvanceorderreqCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}

	//授信
	public static void grantCredit(int sellerId) {
		try {
			GrantCreditReqBean grantcreditreqBean = new GrantCreditReqBean();
			GrantCreditReqCall grantcreditreqCall = new GrantCreditReqCall();
			grantcreditreqBean.setSellerId(sellerId);
			grantcreditreqCall.setData(false, grantcreditreqBean);
			grantcreditreqCall.callService();

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	//创建预支单，并授信
	public static Map createAdvanceOrderAndGrantcredit() {
		Map map = createAdvanceOrder();
		int sellerId = (Integer) map.get("sellerId");
		int orderId = (Integer) map.get("orderId");
		AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
		try {
			Thread.sleep(30000);
			//授信
			grantCredit(sellerId);

			//advance_order
			Map advance = new HashMap();
			advance.put("order_id", orderId);
			// List<AdvanceOrder> advanceOrderList=new ArrayList<AdvanceOrder>();
			AdvanceOrder advanceOrder = new AdvanceOrder();
			advanceOrder = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance).get(0);
			int count = 0;
			while (advanceOrder.getAdvance_status() == 1 && count < 100) {
				Thread.sleep(3000);
				//再授信
				grantCredit(sellerId);
				advanceOrder = advanceOrderDefaultWapper.selectAdvanceOrder(
						advance).get(0);
				Logger.debug("advanceOrder.getAdvance_status()"
						+ advanceOrder.getAdvance_status());
				count++;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return map;
	}

	//创建申请过预支的订单
	public static Map createAdvanceOrderAndApply() {
		Map map = createAdvanceOrderAndGrantcredit();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int orderId = (Integer) map.get("orderId");
		int sellerId = (Integer) map.get("sellerId");
		ApplyAdvanceBillBean applyadvancebillBean = new ApplyAdvanceBillBean();
		ApplyAdvanceBillCall applyadvancebillCall = new ApplyAdvanceBillCall();

		AdvanceOrderDefaultWapper advanceOrderDefaultWapper = new AdvanceOrderDefaultWapper();
		//advance_order
		Map advance = new HashMap();
		advance.put("order_id", orderId);
		try {
			List<AdvanceOrder> advanceOrderList = advanceOrderDefaultWapper
					.selectAdvanceOrder(advance);
			BigDecimal advanced_amount = advanceOrderList.get(0)
					.getCan_advance_amount();
			map.put("advanced_amount", advanced_amount);
			applyadvancebillBean.setSellerId(sellerId);
			applyadvancebillBean.setAdvanceAmount(advanced_amount);
			applyadvancebillBean.setServiceFee(BigDecimal.ONE);
			applyadvancebillCall.setData(applyadvancebillBean);
			applyadvancebillCall.callService();

			map.put("billId", applyadvancebillCall.getData().get("billId"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return map;
	}
	//清理脏数据，将该商家下所有能够预支的金额全部预支
	public static void applyAdvanceAllBill() {
		try {
			ApplyAdvanceBillBean applyadvancebillBean2 = new ApplyAdvanceBillBean();
			ApplyAdvanceBillCall applyadvancebillCall2 = new ApplyAdvanceBillCall();
			int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
			BigDecimal can_advanced_amount = AdvanceOrderService
					.getSellerAdvanceinforeq(sellerId);
			applyadvancebillBean2.setSellerId(sellerId);
			applyadvancebillBean2.setAdvanceAmount(can_advanced_amount);
			applyadvancebillBean2.setServiceFee(BigDecimal.ONE);
			applyadvancebillCall2.setData(false, applyadvancebillBean2);
			applyadvancebillCall2.callService();
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	public static BigDecimal getSellerAdvanceinforeq(int sellerId) {
		BigDecimal can_advanced_amount = BigDecimal.ZERO;
		try {
			GetSellerAdvanceInfoReqBean getselleradvanceinforeqBean = new GetSellerAdvanceInfoReqBean();
			GetSellerAdvanceInfoReqCall getselleradvanceinforeqCall = new GetSellerAdvanceInfoReqCall();
			getselleradvanceinforeqBean.setSellerId(sellerId);
			getselleradvanceinforeqCall.setData(false,
					getselleradvanceinforeqBean);
			getselleradvanceinforeqCall.callService();

			can_advanced_amount = getselleradvanceinforeqCall
					.getSellerAdvanceInfo().getGrantedAmount();
		} catch (Exception e) {
			// TODO: handle exception
			Logger.debug(e);
		}
		return can_advanced_amount;

	}

	public static void main(String args[]) {

		//多少个线程
		for (int i = 0; i < 4; i++) {
			Logger.debug("******************Thread " + (i + 1)
					+ "*******************");
			new Thread(() -> {
				try {
					//单个线程跑多少次
					for (int j = 0; j < 20; j++) {
						Logger.debug("******************第" + j
								+ "次*******************");
						// T.c2cTrading();
						createAdvanceOrder();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}).start();

		}

	}
}
